import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 这是一个简单的自定义列表，充当具体聚合
 *
 * @author Liu Yicong
 * @date 2025/9/23
 */
public class MyList implements Iterable<String> {
	private String[] elements;
	private int count;

	public MyList(int capacity) {
		elements = new String[capacity];
		count = 0;
	}

	public void add(String element) {
		if (count < elements.length) {
			elements[count++] = element;
		}
	}

	// 核心：实现 Iterable 接口，返回自定义迭代器
	@Override
	public Iterator<String> iterator() {
		return new MyListIterator();
	}

	/**
	 * MyList 的具体迭代器，作为内部类实现
	 */
	private class MyListIterator implements Iterator<String> {
		private int currentIndex = 0;

		@Override
		public boolean hasNext() {
			// 内部逻辑：判断是否还有下一个元素
			return currentIndex < count;
		}

		@Override
		public String next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			return elements[currentIndex++];
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException("Remove not supported.");
		}
	}
}
